package com.yupi.apigateway;

import com.yupi.apicommon.model.entity.InterfaceInfo;
import com.yupi.apicommon.model.entity.User;
import com.yupi.apicommon.service.InnerInterfaceInfoService;
import com.yupi.apicommon.service.InnerUserInterfaceInfoService;
import com.yupi.apicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.example.apiclientsdk.utils.SignUtils;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {


    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;
    //设置白名单
    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    private static final String GATEWAY_API_HOST = "http://localhost:8123";
    /**
     * 全局过滤
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1 请求日志
        ServerHttpRequest request = exchange.getRequest();
        String path=GATEWAY_API_HOST+request.getPath().value();
        String method=request.getMethod().toString();
        log.info("请求唯一标识id：" + request.getId());
        log.info("请求路径：" + path);
        log.info("请求方法：" + method);
        log.info("请求参数：" + request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求来源地址：" + sourceAddress);
        log.info("请求来源地址：" + request.getRemoteAddress());
        ServerHttpResponse response = exchange.getResponse();
        // 2 黑白名单   使用白名单
        if (!IP_WHITE_LIST.contains(sourceAddress)){
            return handleNoAuth(response);
        }
        // 3 API网关对用户鉴权（判断ak，sk是否正确）
        HttpHeaders headers = request.getHeaders();

        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String body = headers.getFirst("body");
        // 实际情况需要去数据库校验,是否分配给用户
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);
        }catch (Exception e){
            log.error("getinvokeUser error",e);
        }
        if (invokeUser==null){
            return handleNoAuth(response);
        }

//        if (!"yupi".equals(accessKey)){
//            return handleNoAuth(response);
//        }
        if (Long.parseLong(nonce)>10000){
            return handleNoAuth(response);
        }
        //时间和当前时间不能超过五分钟
        Long currentTime = System.currentTimeMillis()/1000;
        final Long FIVE_MINUTES = 60*5L;
        if (Math.abs(currentTime-Long.parseLong(timestamp))>=FIVE_MINUTES){
            return handleNoAuth(response);
        }
        //一般是从数据库查到的secretKey
        String secretKey = invokeUser.getSecretKey();
        String serverSign = SignUtils.getSign(body, secretKey);
        if (sign==null || !sign.equals(serverSign)){
            return handleNoAuth(response);
        }
        // 4 请求模拟接口是否存在,请求方法是否匹配
        InterfaceInfo interfaceInfo = null;
        try {
            interfaceInfo= innerInterfaceInfoService.getInterfaceInfo(path, method);
        }catch (Exception e){
            log.error("getinterfaceInfo error",e);
        }
        if (interfaceInfo==null){
            return handleNoAuth(response);
        }
        //todo 是否还有调用次数

        // 5 响应日志,调用模拟接口,请求转发
        //Mono<Void> filter=chain.filter(exchange);
        //return filter;
        return handleResponse(exchange, chain,interfaceInfo.getId(), invokeUser.getId());
    }

    /**
     * 处理响应
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,long interfaceInfoId,long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            //缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                //装饰 增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    //等调用完转发的接口拿到返回值才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            //往返回值里面写数据
                            return super.writeWith(fluxBody.map(dataBuffers -> {
                                //7 调用成功后，调用次数+1
                                try{
                                    innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                }catch (Exception e){
                                    log.error("invokeCount error",e);
                                }

                                byte[] content = new byte[dataBuffers.readableByteCount()];
                                dataBuffers.read(content);
                                DataBufferUtils.release(dataBuffers);//释放掉内存

                                // 构建返回日志
                                StringBuilder sb2 = new StringBuilder(200);
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                String data = new String(content, StandardCharsets.UTF_8);
                                // 打印日志
                                sb2.append(data);//data是响应结果
                                log.info("响应结果"+data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {

                            // 8 调用失败，返回一个规范的状态码
                            log.error("<-- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                //设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);// 降级处理返回数据
        }catch(Exception e){
            log.error("网关处理响应异常",e);
            return chain.filter(exchange);
        }
    }
    @Override
    public int getOrder() {
        return -1;
    }

    public Mono<Void> handleNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        // 返回
        return response.setComplete();
    }

    public Mono<Void> handleInvokeError(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        // 返回
        return response.setComplete();
    }
}